/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * Principal.java
 *
 * Created on 12/07/2012, 06:29:01 PM
 */
package vista;

import comunicacion.Comunicacion;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.StringTokenizer;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;

/**
 *
 * @author usuario1
 */
public class Principal extends javax.swing.JFrame {

    /** Creates new form Principal */
    InputStream in;
    OutputStream out;
    Thread hiloLectura;
    boolean bandStart=false;
    public Principal() {
        initComponents();
        try {//abre el puerto para la comunicacion
            this.setSize(340, 340);
            this.setLocation(300, 200);
            Comunicacion comm1 = new Comunicacion();
            comm1.connect("COM1");
            this.in = comm1.in;
            this.out = comm1.out;
            hiloLectura= new Thread(new SerialReader(in));//inicia el hilo para esperar lectura
            hiloLectura.start();
            bandStart=true;
        } catch (Exception e) {

            e.printStackTrace();
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jButton4 = new javax.swing.JButton();
        jLabel4 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        lista1 = new javax.swing.JComboBox();
        jLabel3 = new javax.swing.JLabel();
        listaAlias = new javax.swing.JComboBox();
        jButton2 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("TRABAJO FINAL - REDES");
        addWindowFocusListener(new java.awt.event.WindowFocusListener() {
            public void windowGainedFocus(java.awt.event.WindowEvent evt) {
                formWindowGainedFocus(evt);
            }
            public void windowLostFocus(java.awt.event.WindowEvent evt) {
                formWindowLostFocus(evt);
            }
        });
        getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        jButton4.setText("SALIR");
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });
        getContentPane().add(jButton4, new org.netbeans.lib.awtextra.AbsoluteConstraints(180, 180, 100, -1));

        jLabel4.setFont(new java.awt.Font("Trebuchet MS", 1, 14));
        jLabel4.setText("CHAT - ENVIO DE ARCHIVOS");
        getContentPane().add(jLabel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(80, 40, -1, -1));

        jButton1.setText("Iniciar chat");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
        getContentPane().add(jButton1, new org.netbeans.lib.awtextra.AbsoluteConstraints(40, 180, 110, -1));

        lista1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                lista1ActionPerformed(evt);
            }
        });
        getContentPane().add(lista1, new org.netbeans.lib.awtextra.AbsoluteConstraints(180, 140, 100, 20));

        jLabel3.setText("CONECTADOS");
        getContentPane().add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(190, 100, -1, -1));

        listaAlias.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                listaAliasActionPerformed(evt);
            }
        });
        getContentPane().add(listaAlias, new org.netbeans.lib.awtextra.AbsoluteConstraints(40, 140, 110, -1));

        jButton2.setText("Agregar alias");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });
        getContentPane().add(jButton2, new org.netbeans.lib.awtextra.AbsoluteConstraints(40, 100, 110, -1));

        pack();
    }// </editor-fold>//GEN-END:initComponents

private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
// TODO add your handling code here:
    System.exit(0);

}//GEN-LAST:event_jButton4ActionPerformed

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
    // TODO add your handling code here:
    //cuando se presiona el boton conectar pide un nombre para login   
    String cad = "1$" + lista1.getSelectedItem().toString() + "$invite?" + lista1.getSelectedItem().toString() + "?" + listaAlias.getSelectedItem().toString() + "?";
    
    enviarMensaje(cad);
    System.out.println(cad);
    //  enviarMensaje("\n");hgfgh

    new chatSERIAL(in, out, listaAlias.getSelectedItem().toString(), lista1.getSelectedItem().toString()).show();

}//GEN-LAST:event_jButton1ActionPerformed

private void lista1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_lista1ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_lista1ActionPerformed

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
// TODO add your handling code here:
    String nombre;
    int ban = 0;
    nombre = JOptionPane.showInputDialog("Ingrese su nombre de LogIn: ");
    
    if (listaAlias.getItemCount() == 0) {
        ban = 0;
    } else {
        for (int i = 0; i < listaAlias.getItemCount(); i++) {
            if (nombre.equals(listaAlias.getItemAt(i))) {
                ban = 1;
            }
        }
    }
    if (ban == 1) {
        JOptionPane.showMessageDialog(rootPane, "Ese nombre ya existe:");

    } else {
        enviarMensaje("00$Log#" + nombre);
        enviarMensaje("\n");
        listaAlias.addItem(nombre);
    }


}//GEN-LAST:event_jButton2ActionPerformed

private void listaAliasActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_listaAliasActionPerformed
// TODO add your handling code here:
    // JOptionPane.showMessageDialog(rootPane,"Elegir con quien chatear:");
}//GEN-LAST:event_listaAliasActionPerformed

private void formWindowLostFocus(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowLostFocus
    // TODO add your handling code here:
    System.out.println("Ya no esta aqui");
    hiloLectura.stop();
}//GEN-LAST:event_formWindowLostFocus

private void formWindowGainedFocus(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowGainedFocus
    // TODO add your handling code here:
    hiloLectura= new Thread(new SerialReader(in));//inicia el hilo para esperar lectura
    hiloLectura.start();
}//GEN-LAST:event_formWindowGainedFocus

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Principal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Principal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Principal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Principal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new Principal().setVisible(true);
            }
        });
    }

    public class SerialReader implements Runnable { //hilo prara lectura

        InputStream in;

        public SerialReader(InputStream in) {
            this.in = in;
        }

        public void run() {
            byte[] buffer = new byte[1024];
            int len = -1;
            try {
                String mensaje = "";
                String cadena = "";



                boolean band = true;//mietras haya bits en el buffer los anexa en una cadena
                while ((len = this.in.read(buffer)) > -1) {

                    if (len > 0) {
                        // System.out.print(len);
                        mensaje = (new String(buffer, 0, len));
                        cadena += mensaje;
                        //System.out.println(mensaje);
                    }
                    if (len > 0 && cadena.contains("?#0")) {
                        System.out.println("cadena->>>" + cadena);
                        if (cadena.contains("$invite"))//si recibe una cadena de login muestra en conectados
                        {
                            StringTokenizer tokens = new StringTokenizer(cadena, "?");
                            tokens.nextToken();
                            String minombre = tokens.nextToken();

                            String invita = tokens.nextToken(); //kien me invita
                            System.out.println("linea1");
                            System.out.println(invita);
                            System.out.println("linea2");
                            System.out.println(minombre);
                            System.out.println("linea3");
                            new chatSERIAL(in, out, minombre, invita).show();
       

                        }

                        if (cadena.contains("$conectedList"))//si recibe una cadena de login muestra en conectados
                        {
                            StringTokenizer tokens = new StringTokenizer(cadena, "#");
                            tokens.nextToken();
                            int numc = Integer.parseInt(tokens.nextToken());
                            String conectados = tokens.nextToken();
                            StringTokenizer tokens1 = new StringTokenizer(conectados, ";");
                            lista1.removeAllItems();
                            for (int i = 0; i < numc; i++) {
                                lista1.addItem(tokens1.nextToken());
                            }
                        }

                        cadena = "";
                    }

                    //$invite#minombre#kieninvita




                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
public void cerrar()
{
    this.dispose();
}
    public void enviarMensaje(String cadena) {
        cadena = cadena + "?#0";
        char[] mensj = cadena.toCharArray();//transfrma el string a cadena de chars 
        //para  luego transformarla en enteros y mandar por el puerto
        byte c = 0;
        int ln = mensj.length;
        for (int i = 0; i < ln; i++) {
            try {
                c = (byte) mensj[i];
                this.out.write(c);//envia la cadena byte por byte
            } catch (IOException ex) {
                Logger.getLogger(chatSERIAL.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton4;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JComboBox lista1;
    private javax.swing.JComboBox listaAlias;
    // End of variables declaration//GEN-END:variables
}
